<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Withdraw;
use app\model\Paymethod;
use app\model\Agent;
use app\model\Technical;
use app\model\Store;
use app\model\Tuanzhang;
use app\model\Operatingcity;
use app\model\UsersRelation;
use app\model\MemberBankcard;
use app\model\Member;
use app\model\Config;
use app\model\Openid;

class WithdrawController extends Base
{

	function getPath()
	{
		$path = input('post.path', '', 'serach_in');
		if (!empty($path)) {
			$tmppath = explode('/', $path);
		}

		return $tmppath;
	}
	function index()
	{
		$weid = weid();
		$path = input('post.path', '', 'serach_in');
		//$mo = input('post.mo', '', 'serach_in');
		$page = input('post.page', 1, 'intval');
		$keyword = input('post.keyword', '', 'serach_in');

        $agentcscl =  Config::setcashservice(Config::getconfig('agent'));
		$technicalcscl =  Config::setcashservice(Config::getconfig('technical'));
		$storecscl =  Config::setcashservice(Config::getconfig('store'));
		$tuanzhangcscl =  Config::setcashservice(Config::getconfig('tuanzhang'));

		$query = Withdraw::where(['weid' => $weid]);

		$mo = $this->getPath()[2];

		if (!empty($mo)) {
			$query->where('mo', $mo);
		}

		if (!empty($this->sid)) {
			$query->where('sid', $this->sid);
		}
		if (!empty($this->ocid)) {
			$query->where('ocid', $this->ocid);
		}
		if (!empty($mo)) {
			$query->where('mo', $mo);
		}

		$res = $query->order('id desc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			$vo['cscl'] = [];
			$vo['sid'] = Store::getTitle($vo['sid']);
			$vo['MemberBankcard'] = MemberBankcard::getbankcard($vo['bid']);
			$vo['username'] = Member::get_name($vo['uid']);
			
			if ($vo['mo'] == 'agent') {
				$vo['cscl'] = $agentcscl[$vo['days']];
			} elseif ($vo['mo'] == 'technical') {
				$vo['cscl'] = $technicalcscl[$vo['days']];
			} elseif ($vo['mo'] == 'store') {
				$vo['cscl'] = $storecscl[$vo['days']];
			} elseif ($vo['mo'] == 'tuanzhang') {
				$vo['cscl'] = $tuanzhangcscl[$vo['days']];
			}
			$vo['pay_time'] = time_format($vo['pay_time']);
			$vo['audit_time'] = time_format($vo['audit_time']);
		}

		$data['data'] = $res;

		return $this->json($data);
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');

		$data = Withdraw::find($id);
		if (!empty($data)) {
			$data = $data->toArray();
			if ($data['mo'] == 'agent') {
				$data['username'] = Agent::getTitle($data['uid']);
			} elseif ($data['mo'] == 'technical') {
				$data['username'] = Technical::getTitle($data['uid']);
			} elseif ($data['mo'] == 'store') {
				$data['username'] = Store::getTitlebyuid($data['uid']);
			} elseif ($data['mo'] == 'tuanzhang') {
				$data['username'] = Tuanzhang::getTitlebyuid($data['uid']);
			}

			$data['MemberBankcard'] = MemberBankcard::getbankcard($data['bid']);
		}

		return $this->json(['data' => $data]);
	}

	public function audit()
	{
		$id = $this->request->post('id');
		$postdata = input('post.');

		try {
			$id = $postdata['id'];
			$data = Withdraw::find($id)?->toArray();
			$res['code'] = false;

			$data['status'] =  $postdata['status'];
			$data['remark'] =  $postdata['remark'];
			$data['audit_time'] = time();
			unset($data['create_time']);

			if ($data['status'] == 1) {

				$MemberBankcard = MemberBankcard::find($data['bid']);
				if (!empty($MemberBankcard)) {
					$MemberBankcard = $MemberBankcard->toArray();
					if ($MemberBankcard['ptype'] == 3) {
						if ($data['pay_from'] == 'mp') {
							$Openid = Openid::getMpOpenidbyuid($MemberBankcard['uid']);
						} else {
							$Openid = Openid::getWxappOpenidbyuid($MemberBankcard['uid']);
						}
						if (!empty($Openid)) {
							$wxpay_settings = Paymethod::getwx_settings();
							$actual_amounts = round($data['actual_amounts'], 2);
							$actual_amounts = intval($actual_amounts * 100);
							if ($wxpay_settings['transfertype'] == '1') {
								$payment = \app\samos\wechat\WxPaymethod::makepay($data['pay_from']);


								$result = $payment->transfer->toBalance([
									'partner_trade_no' => $data['withdraw_sn'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
									'openid' => $Openid,
									'check_name' => 'FORCE_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
									're_user_name' => $MemberBankcard['name'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
									'amount' => $actual_amounts, // 企业付款金额，单位为分
									'desc' => '提现', // 企业付款操作说明信息。必填
								]);

								if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
									$res['code'] = Withdraw::update($data);
								} else {
									$res['code'] = false;
									$res['return_msg'] = $result['return_msg'];
									$res['err_code_des'] = $result['err_code_des'];
								}
							} elseif ($wxpay_settings['transfertype'] == '2') {
								$payment = \app\samos\wechat\WxPaymethod::makeTransferspayv3($data['pay_from']);

								$result = $payment->batchs([
									'out_batch_no'         => 'plfk' . $data['withdraw_sn'],
									'batch_name'           => '用户佣金提现',
									'batch_remark'         => '用户佣金提现',
									'total_amount'         => $actual_amounts,
									'transfer_detail_list' => [
										[
											'out_detail_no'   => $data['withdraw_sn'],
											'transfer_amount' => $actual_amounts,
											'transfer_remark' => '用户佣金提现',
											'openid'          => $Openid,
											'user_name'       => ''
										]
									]
								]);
								if (isset($result['code']) && isset($result['message'])) {
									$res['code'] = false;
									$res['return_msg'] = $result['message'];
									$res['err_code_des'] = $result['err_code_des'];
								} else {
									$res['code'] = Withdraw::update($data);
								}
							} else {
								$res['code'] = Withdraw::update($data);
							}
						}
					} else {
						$res['code'] = Withdraw::update($data);
					}
				}
			} else {
				if ($data['status'] == 2) {

					$uid = $data['uid'];
					$reid = UsersRelation::getreid($uid, $data['mo']);

					if ($data['mo'] == 'agent') {
						$moapply =  Agent::where('uid', $uid)->find();
						$moapplyid = $moapply->id;
						$model =  new Agent;
					} elseif ($data['mo'] == 'technical') {
						$moapply =  Technical::find($reid);
						$moapplyid = $moapply->id;
						$model =  new Technical;
					} elseif ($data['mo'] == 'tuanzhang') {
						$moapply =  Tuanzhang::find($reid);
						$moapplyid = $moapply->id;
						$model =  new Tuanzhang;
					} elseif ($data['mo'] == 'store') {
						$moapply = Store::getInfobyuid($uid);
						$moapplyid = $moapply['id'];
						$model =  new Store;
					} elseif ($data['mo'] == 'operatingcity') {
						$moapply =  Operatingcity::find($reid);
						$moapplyid = $moapply->id;
						$model =  new Operatingcity;
					}

					$model->where('id', $moapplyid)->inc('income', $data['amounts'])->update();
				}
				if (!empty($data)) {
					$res['code'] = Withdraw::update($data);
				}
			}
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}

		if (!empty($res['code'])) {
			return $this->json(['msg' => '操作成功']);
		} else {
			return $this->json(['msg' => $res['return_msg'] . $res['err_code_des']]);
		}
	}

	function delete()
	{
		return $this->del(new Withdraw());
	}
}
